package com.yilin.platform.controller.message;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yilin.platform.base_core.application.BaseController;
import com.yilin.platform.base_core.application.PageData;
import com.yilin.platform.base_core.application.ReturnData;
import com.yilin.platform.base_core.commons.annotation.Explain;
import com.yilin.platform.base_core.commons.annotation.NotNull;
import com.yilin.platform.base_core.commons.annotation.SkipLoginVerify;
import com.yilin.platform.base_core.commons.annotation.UserTarget;
import com.yilin.platform.base_core.commons.utils.ParamUtil;
import com.yilin.platform.base_core.tools.QueryUtil;
import com.yilin.platform.entity.enums.user.UserType;
import com.yilin.platform.entity.message.PushRecord;
import com.yilin.platform.entity.user.Account;
import com.yilin.platform.service.impl.message.MessageData;
import com.yilin.platform.service.impl.user.AccountService;
import com.yilin.platform.service.message.IPushService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 推送控制器
 *
 * @author zhangjinyuan
 * @date 2022/10/26
 */
@RestController
@RequestMapping("/message/push/")
public class PushController extends BaseController {

    @Resource
    IPushService pushService;

    @Resource
    AccountService accountService;


    @GetMapping("/push")
    public String push(@RequestParam String openid, @RequestParam String formid) {
        //1,配置小程序信息
        WxMaInMemoryConfig wxConfig = new WxMaInMemoryConfig();
        wxConfig.setAppid("wx09c8d47d5183e31a");//小程序appid
        wxConfig.setSecret("95bbb95409a7a0f7879e81b56e069178");//小程序AppSecret

        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxConfig);

        //2,设置模版信息（keyword1：类型，keyword2：内容）
        List<WxMaTemplateData> templateDataList = new ArrayList<>(2);
        WxMaTemplateData data1 = new WxMaTemplateData("keyword1", "获取老师微信");
        WxMaTemplateData data2 = new WxMaTemplateData("keyword2", "测试1");
        WxMaTemplateData data3 = new WxMaTemplateData("keyword3", "测试2");
        WxMaTemplateData data4 = new WxMaTemplateData("keyword4", "测试3");
        templateDataList.add(data1);
        templateDataList.add(data2);
        templateDataList.add(data3);
        templateDataList.add(data4);
        //3，设置推送消息
        WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder()
                .toUser(openid)//要推送的用户openid
                .formId(formid)//收集到的formid
                .templateId("yK_HiihLN4lkcYilih_uvmpRQuzIwLw519VcqRH2JqE")//推送的模版id（在小程序后台设置）
                .data(templateDataList)//模版信息
                .page("pages/home/index")//要跳转到小程序那个页面
                .build();
        //4，发起推送
        try {wxMaService.getMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            System.out.println("推送失败：" + e.getMessage());
            return e.getMessage();
        }
        return "推送成功";
    }





    /**
     * 获取推送记录分页
     */
    @PostMapping(value = "getNotificationPage")
    @NotNull({"page", "limit"})
    public ReturnData<PageData<PushRecord>> getNotificationPage(PushRecord query, @Explain("页码") Integer page, @Explain("条数") Integer limit) {
        PageData<PushRecord> pageData = pushService.page(new PageData<>(page, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(),query));
        return jsonView(true, "获取成功", pageData);
    }

    /**
     * 根据日期删除推送记录
     */
    @PostMapping(value = "pushDeleteByDate")
    @NotNull({"startDate", "endDate"})
    public ReturnData<Object> pushDeleteByDate(@Explain("开始日期") String startDate, @Explain("结束日期") String endDate) {
        pushService.deleteByDate(startDate, endDate);
        return jsonView(true, "删除成功");
    }

    /**
     * 根据id删除推送记录
     */
    @PostMapping(value = "pushDeleteByIds")
    @NotNull("ids")
    public ReturnData<Object> pushDeleteByIds(@Explain("ID数组") String[] ids) {
        pushService.removeByIds(Arrays.asList(ids));
        return jsonView(true, "删除消息成功");
    }

    //----------------------------------------------------------推送功能区------------------------------------------------

    /**
     * 核心推送1
     * 根据用户推送(socket+极光推送)
     */
    @PostMapping(value = "sendSystemNotify")
    @NotNull({"toAccountId","text"})
    @SkipLoginVerify
    public ReturnData<Object> sendSystemNotify(@Explain("接受人ID") String toAccountId, @Explain("消息内容") String text, String originalUrl) {
        Account toAccount = accountService.getAccountById(toAccountId);
        ParamUtil.isNull(toAccount, "未查询到接收用户");
        pushService.sendNotificationByUser(toAccount,  MessageData.MessageType.notice, MessageData.DataType.text, text, originalUrl);
        return jsonView(true, "发送成功");
    }

    /**
     * 核心推送2
     * 根据用户推送(socket+极光推送)
     */
    @PostMapping(value = "sendOrderNotify")
    @NotNull({"toAccountId", "text"})
    @SkipLoginVerify
    public ReturnData<Object> sendOrderNotify(@Explain("接受人ID") String toAccountId, @Explain("消息内容") String text, String originalUrl) {
        Account toAccount = accountService.getAccountById(toAccountId);
        ParamUtil.isNull(toAccount, "未查询到接收用户");
        pushService.sendNotificationByUser(toAccount,  MessageData.MessageType.order, MessageData.DataType.order, text, originalUrl);
        return jsonView(true, "发送成功");
    }

    /**
     * 更新推送标识(极光推送)
     */
    @PostMapping(value = "updateAliasAndTag")
    @NotNull({"pushId", "alias", "tag"})
    @UserTarget({UserType.shipperUser, UserType.truckerUser})
    public ReturnData<Object> updateAliasAndTag(String pushId, String alias, String tag) {
        pushService.updateAliasAndTag(getLoginUser(), pushId, alias, tag);
        return jsonView(true, "更新成功");
    }
}
